package com.yzz.shopping.ui.fragment

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.yzz.shopping.R
import com.yzz.shopping.entity.GlideRecommendBean
import com.yzz.shopping.ui.activity.ShoppingSearchActivity
import com.yzz.shopping.ui.activity.ShoppingWebviewActivity
import com.yzz.shopping.ui.adapter.ShoppingAdapter
import com.yzz.shopping.utils.BackToTopUtils
import com.yzz.shopping.utils.NoFastClickUtils
import com.yzz.shopping.utils.ToastUtils
import com.yzz.shopping.viewmodel.GlideViewModel
import kotlinx.android.synthetic.main.fragment_shopping.*
import kotlinx.android.synthetic.main.item_custom_search.*


/**
 * @Author : yangzuozhe
 * @Time : On 2022/2/23 14:49
 *
 * @Description : ShoppingFragment
 */
class ShoppingFragment : Fragment() {

    private var mViewModel: GlideViewModel? = null
    private var mShoppingAdapter: ShoppingAdapter? = null
    private val SEARCH_URL = "http://shop.wukongfenshen.com/v/search?keyword="
    private var mIsHomePage: Boolean = true
    private var IS_MAIN_NESTED = false
    private var ismShowTitle = true

    companion object {
        private const val IS_SHOW_TITLE = "IS_SHOW_TITLE"
        private const val IS_HOME_PAGE = "IS_HOME_PAGE"
        private const val IS_MAIN_NESTED_KEY = "IS_MAIN_NESTED_KEY"

        fun newInstance(
            /**
             * 主页是否嵌套
             */
            isMainNested: Boolean,
            /**
             * 是否展示title
             */
            isShowTitle: Boolean,
            /**
             * 是否是首页数据
             */
            isHomePage: Boolean,
        ): ShoppingFragment {
            val args = Bundle()
            args.putBoolean(IS_SHOW_TITLE, isShowTitle)
            args.putBoolean(IS_HOME_PAGE, isHomePage)
            args.putBoolean(IS_MAIN_NESTED_KEY, isMainNested)
            val fragment = ShoppingFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return LayoutInflater.from(context).inflate(R.layout.fragment_shopping, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        initView()
        initViewModel()
    }

    private fun initView() {
        arguments?.let {
            ismShowTitle = it.getBoolean(IS_SHOW_TITLE, false)
            mIsHomePage = it.getBoolean(IS_HOME_PAGE, false)
            IS_MAIN_NESTED = it.getBoolean(IS_MAIN_NESTED_KEY, false)
        }
        if (!ismShowTitle) {
            mTvShopping.visibility = View.GONE
        }
        initEmptyView()
        initSwip()
        initSearchView()
    }

//    private fun initSearchView() {
//        mEdShoppingShopping?.setOnClickListener {
//            showSoftInput(it)
//        }
//        mEdShoppingShopping?.setOnEditorActionListener { v, actionId, event ->
//            when (actionId) {
//                EditorInfo.IME_ACTION_SEARCH -> {
//                    searchWeb()
//                }
//            }
//            true
//        }
//        mTvShoppingSearchYes?.setOnClickListener {
//            searchWeb()
//        }
//        mIvShoppingBack?.visibility = View.GONE
//    }

    private fun initSearchView() {
        llShoppingSearch?.setOnClickListener {
            if (NoFastClickUtils.isFastClick()) {
                return@setOnClickListener
            }
            launchSearchActivity()
        }
    }

    private fun searchWeb() {
        val text = mEdShoppingShopping?.text
        if (!TextUtils.isEmpty(text)) {
            hideSoftInput(mEdShoppingShopping)
            launchWebActivity(SEARCH_URL + text)
        } else {
            ToastUtils.showLong(context, "请输入内容")
        }
    }

    private fun showSoftInput(view: View) {
        val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        //显示键盘
        imm?.showSoftInput(view, InputMethodManager.SHOW_FORCED)
    }

    private fun hideSoftInput(view: View?) {
        if (view != null) {
            val imm =
                activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
            //ps：这是强制隐藏键盘的代码，因此如果想要显示键盘用上面那句话，隐藏键盘用下面这句话
            imm?.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }


    private fun initSwip() {
        mSmartRefresh?.setRefreshHeader(ClassicsHeader(context))
        mSmartRefresh?.setRefreshFooter(ClassicsFooter(context))
        mSmartRefresh?.setOnRefreshListener {
            requestData(true)
        }
        mSmartRefresh?.setOnLoadMoreListener {
            requestData(false)
        }
    }

    private fun initEmptyView() {
        mShoppingEmptyView?.setRetryCLick {
            setEmptyShow(false)
            if (mShoppingAdapter == null) {
                requestData(true)
            } else {
                requestData(false)
            }
        }
    }

    private fun initViewModel() {
        mViewModel = ViewModelProvider(this).get(GlideViewModel::class.java)
        mViewModel?.glideRecommendBeanLiveData?.observe(viewLifecycleOwner) { pair: Pair<Int, ArrayList<GlideRecommendBean?>?>? ->
            onSuccess(pair)
        }
        mViewModel?.homeRecommendBeanLiveData?.observe(viewLifecycleOwner) { pair: Pair<Int, ArrayList<GlideRecommendBean?>?>? ->
            onSuccess(pair)
        }
        requestData(true)
    }

    private fun onSuccess(pair: Pair<Int, ArrayList<GlideRecommendBean?>?>?) {
        if (pair != null) {
            initData1(pair)
        } else {
            mSmartRefresh?.finishLoadMore(false)
            mSmartRefresh?.finishRefresh(false)
            if (mShoppingAdapter == null) {
                setEmptyShow(true)
            } else {
                setEmptyShow(false)
            }
        }
    }


    private fun initData1(pair: Pair<Int, ArrayList<GlideRecommendBean?>?>) {
        val page = pair.first
        val bean = pair.second
        setEmptyShow(false)
        if (mShoppingAdapter == null) {
            if (bean != null) {
                mSmartRefresh?.finishRefresh(true)
                mSmartRefresh?.finishLoadMore(true)
                val ac = activity
                if (ac != null) {
                    mShoppingAdapter = ShoppingAdapter(ac, bean, false)
                    mRvShopping?.adapter = mShoppingAdapter
                    mRvShopping?.layoutManager =
                        StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
                    BackToTopUtils.instance.initBackToTop(IS_MAIN_NESTED, mRvShopping, mIvBackToTop)
                }
            } else {
                mSmartRefresh?.finishLoadMore(false)
                mSmartRefresh?.finishRefresh(false)
                setEmptyShow(true)
            }
        } else {
            if (page == 1) {
                bean?.let { mShoppingAdapter?.refreshData(it) }
                mSmartRefresh?.finishRefresh(true)
            } else {
                if (bean != null) {
                    mShoppingAdapter?.loadMore(bean)
                }
                mSmartRefresh?.finishLoadMore(true)
            }
        }


    }


    private fun setEmptyShow(boolean: Boolean) {
        mShoppingSpinkView?.visibility = View.GONE
        mShoppingEmptyView?.setEmptyIsShow(boolean)
    }

    private fun launchWebActivity(url: String) {
        val intent = Intent(context, ShoppingWebviewActivity::class.java)
        intent.putExtra(ShoppingWebviewActivity.URL, url)
        context?.startActivity(intent)
    }

    private fun launchSearchActivity() {
        val intent = Intent(context, ShoppingSearchActivity::class.java)
        context?.startActivity(intent)
    }

    private fun requestData(isFirst: Boolean) {
        if (mIsHomePage) {
            mViewModel?.requestHomeRecommend(GlideViewModel.IEcType.JU_HE, isFirst)
        } else {
            mViewModel?.requestRecommend(GlideViewModel.IEcType.JU_HE, isFirst)
        }
    }

}